package com.xtc.netty.io.nio.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @author Administrator
 */
public class NioChatClient {

    private final InetSocketAddress serverAdrress = new InetSocketAddress("localhost", 9090);
    private Selector selector = null;
    private SocketChannel client = null;

    private String nickName = "";
    private Charset charset = Charset.forName("UTF-8");
    private static String USER_EXIST = "系统提示：该昵称已经存在，请换一个昵称";
    private static String USER_CONTENT_SPILIT = "#@#";

    public NioChatClient() {
        try {
            selector = Selector.open();

            this.client = SocketChannel.open(serverAdrress);
            this.client.configureBlocking(false);

            this.client.register(selector, SelectionKey.OP_READ);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void session() {
        new Reader().start();

        new Writer().start();
    }

    private class Reader extends Thread {
        @Override
        public void run() {

            try {
                while (true) {
                    int select = selector.select();
                    if (select == 0) {
                        continue;
                    }

                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();

                        iterator.remove();;
                        
                        process(key);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        private void process(SelectionKey key) throws IOException {
            if (key.isReadable()) {
                SocketChannel clinet = (SocketChannel) key.channel();

                ByteBuffer buffer = ByteBuffer.allocate(1024);
                String content = "";
                while (clinet.read(buffer) > 0) {
                    buffer.flip();

                    content += charset.decode(buffer);
                }

                if (USER_CONTENT_SPILIT.equals(content)) {
                    nickName = "";
                }
                System.out.println(content);

                key.interestOps(SelectionKey.OP_READ);
            }
        }
    }

    private class Writer extends Thread {
        @Override
        public void run() {
            Scanner scanner = new Scanner(System.in);
            try {
                while (scanner.hasNextLine()) {
                    String line = scanner.nextLine();
                    if ("".equals(line)) {
                        continue;
                    }

                    if ("".equals(nickName)) {
                        nickName = line;
                        line = nickName + USER_CONTENT_SPILIT;
                    } else {
                        line = nickName + USER_CONTENT_SPILIT + line;
                    }

                    client.write(charset.encode(line));
                }
                scanner.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        new NioChatClient().session();
    }
}
